<?php

namespace App\Services\Aes;

//use function Laravel\Prompts\select;

class AES
{
    private string $iv = '' ;//盐
    private string $key = ''; //私钥


    public function __construct()
    {
        $this->iv = env("AES_ALGORITHM_IV");
        $this->key = env("AES_ALGORITHM_KEY");
    }

    /**
     * 实列化
     * @param string $text 需要加解密的字符串
     * @param bool $type true=>解密 false=>加密
     * @return string 加解密后的的字符串
     */
    private function main(string $text , bool $type=false):string{
        if($type){
            return openssl_decrypt($text, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $this->iv);
        }
        return openssl_encrypt($text, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $this->iv);
    }
    /**
     * AES-256-CBC 加密
     * @param string $text
     * @return string
     */
    public function encrypt(string $text):string
    {
        return base64_encode(self::main($text));
    }

    /**
     * AES-256-CBC 解密
     * @param string $text
     * @return string
     */
    public function decrypt(string $text):string
    {
        return self::main(base64_decode($text),true);
    }

}


